using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.IO;
using ESecretary.WinUI;
using System.Threading;
using ESecretary.MyCommon;
using ESecretary.DataEntity;

namespace ESecretary.Socket
{

    public delegate void TextMsgReceiveEventHandler(object sender,ReceiveEventArgs args);

    public class MySocket
    {        
        private static UdpClient client;
        private static TcpListener server;

        public static TcpListener FileServer
        {
            get
            {
                if (server == null)
                {
                    server = new TcpListener(IPAddress.Any,MyConfig.LocalPort);
                }
                return server;                
            }
        }

        public event TextMsgReceiveEventHandler MsgReceived;       

        public MySocket()
        {            
            if (client == null)
            {
                client = new UdpClient(MyConfig.LocalPort);
            }
        }

        public void Send(MsgInfo info,IPEndPoint point)
        {
            byte[] msg = MyCommon.Utility.Serialize(info);
            client.Send(msg, msg.Length, point);
        }

        public void Send(MsgInfo info, ChatUserInfo user)
        {
            Send(info, user.EndPoint);
        }

        public void Send(MsgInfo info, IPEndPoint[] points)
        {
            byte[] msg = MyCommon.Utility.Serialize(info);
            foreach (IPEndPoint point in points)
            {
                client.Send(msg, msg.Length, point);                
            }
        }

        public void Send(MsgInfo info, ChatUserInfo[] users)
        {
            foreach (ChatUserInfo user in users)
            {
                Send(info, user.EndPoint);
            }
        }

        public void Listen()
        {
            Thread lis = new Thread(new ThreadStart(Receive));
            lis.IsBackground = true;
            lis.Start();
        }

        private void Receive()
        {
            IPEndPoint remote=new IPEndPoint(IPAddress.Parse(Utility.GetIPAddress()),MyConfig.LocalPort);
            while (true)
            {
                byte[] buffer = client.Receive(ref remote);
                object msg = MyCommon.Utility.Deserialize(buffer);
                MsgInfo info = (MsgInfo)msg;
                info.User.EndPoint = remote;
                ReceiveEventArgs args = new ReceiveEventArgs(info);
                MsgReceived(this, args);
            }
        }       
    }
}
